package com.yupi.yupicturebackend.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yupi.yupicturebackend.exception.BusinessException;
import com.yupi.yupicturebackend.exception.ErrorCode;
import com.yupi.yupicturebackend.exception.ThrowUtils;
import com.yupi.yupicturebackend.model.entity.Picture;
import com.yupi.yupicturebackend.model.entity.Space;
import com.yupi.yupicturebackend.model.entity.User;
import com.yupi.yupicturebackend.model.enums.SpaceLevelEnum;
import com.yupi.yupicturebackend.model.req.space.SpaceAddRequest;
import com.yupi.yupicturebackend.model.req.space.SpaceQueryRequest;
import com.yupi.yupicturebackend.model.vo.PictureVO;
import com.yupi.yupicturebackend.model.vo.SpaceVO;
import com.yupi.yupicturebackend.model.vo.UserVO;
import com.yupi.yupicturebackend.service.SpaceService;
import com.yupi.yupicturebackend.mapper.SpaceMapper;
import com.yupi.yupicturebackend.service.UserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

/**
* @author 86178
* @description 针对表【space(空间)】的数据库操作Service实现
* @createDate 2025-04-10 16:06:35
*/
@Service
public class SpaceServiceImpl extends ServiceImpl<SpaceMapper, Space>
    implements SpaceService{

    @Resource
    private UserService userService;

    @Resource
    private TransactionTemplate transactionTemplate;


    /**
     * 校验空间
     * @param space
     * @param add
     */
    @Override
    public void validSpace(Space space ,Boolean add) {
        ThrowUtils.throwIf(space==null, ErrorCode.PARAMS_ERROR);
        String spaceName = space.getSpaceName();
        Integer spaceLevel = space.getSpaceLevel();
        SpaceLevelEnum spaceLevelEnum = SpaceLevelEnum.getEnumByValue(spaceLevel);
        //如果是创建空间校验
        if(add){
            ThrowUtils.throwIf(StrUtil.isBlank(spaceName), ErrorCode.PARAMS_ERROR,"空间名称不能为空");
            ThrowUtils.throwIf(spaceLevel==null, ErrorCode.PARAMS_ERROR,"空间级别不能为空");
        }
        //如果是修改空间校验
        if(spaceLevel!=null&&spaceLevelEnum==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"空间级别错误");
        }
        if(spaceName!=null&& spaceName.length()>30){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"空间名称不能超过30个字符");
        }
    }


    /**
     * 获取查询对象
     * @param spaceQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<Space> getQueryWrapper(SpaceQueryRequest spaceQueryRequest) {
        QueryWrapper<Space> queryWrapper = new QueryWrapper<>();
        if(spaceQueryRequest==null){
            return queryWrapper;
        }
        Long id = spaceQueryRequest.getId();
        Long userId = spaceQueryRequest.getUserId();
        String spaceName = spaceQueryRequest.getSpaceName();
        Integer spaceLevel = spaceQueryRequest.getSpaceLevel();
        String sortField = spaceQueryRequest.getSortField();
        String sortOrder = spaceQueryRequest.getSortOrder();

        queryWrapper.eq(ObjUtil.isNotEmpty(id),"id",id);
        queryWrapper.eq(ObjUtil.isNotEmpty(userId),"userId",userId);
        queryWrapper.eq(ObjUtil.isNotEmpty(spaceLevel),"spaceLevel",spaceLevel);

        queryWrapper.like(StrUtil.isNotBlank(spaceName),"spaceName",spaceName);
        // 排序
        queryWrapper.orderBy(StrUtil.isNotEmpty(sortField), sortOrder.equals("ascend"), sortField);

        return queryWrapper;
    }

    /**
     * 获取VO对象
     * @param space
     * @param request
     * @return
     */
    @Override
    public SpaceVO getSpaceVO(Space space, HttpServletRequest request) {
        SpaceVO spaceVO = SpaceVO.objToVo(space);
        Long userId = space.getUserId();
        if(userId!=null && userId>0){
            User user = userService.getById(userId);
            if(user!=null){
                UserVO userVO = userService.getUserVO(user);
                spaceVO.setUser(userVO);
            }
        }
        return spaceVO;
    }

    /**
     * 分页获取空间的封装类
     * @param spacePage
     * @param request
     * @return
     */
    @Override
    public Page<SpaceVO> getSpaceVOPage(Page<Space> spacePage, HttpServletRequest request) {
        List<Space> spaceList = spacePage.getRecords();
        Page<SpaceVO> spaceVOPage = new Page<>(spacePage.getCurrent(), spacePage.getSize(), spacePage.getTotal());
        if (CollUtil.isEmpty(spaceList)) {
            return spaceVOPage;
        }
        // 对象列表 => 封装对象列表
        List<SpaceVO> spaceVOList = spaceList.stream().map(SpaceVO::objToVo).collect(Collectors.toList());
        // 1. 关联查询用户信息
        Set<Long> userIdSet = spaceList.stream().map(Space::getUserId).collect(Collectors.toSet());
        Map<Long, List<User>> userIdUserListMap = userService.listByIds(userIdSet).stream()
                .collect(Collectors.groupingBy(User::getId));
        // 2. 填充信息
        spaceVOList.forEach(spaceVO -> {
            Long userId = spaceVO.getUserId();
            User user = null;
            if (userIdUserListMap.containsKey(userId)) {
                user = userIdUserListMap.get(userId).get(0);
            }
            spaceVO.setUser(userService.getUserVO(user));
        });
        spaceVOPage.setRecords(spaceVOList);
        return spaceVOPage;
    }

    /**
     * 根据空间等级填充空间的参数
     * @param space
     */
    @Override
    public void fillSpaceBySpaceLevel(Space space) {
        SpaceLevelEnum spaceLevelEnum = SpaceLevelEnum.getEnumByValue(space.getSpaceLevel());
        if(spaceLevelEnum!=null){
            long maxCount = spaceLevelEnum.getMaxCount();
            if(space.getMaxCount()==null){
                space.setMaxCount(maxCount);
            }
            long maxSize = spaceLevelEnum.getMaxSize();
            if(space.getMaxSize()==null){
                space.setMaxSize(maxSize);
            }
        }
    }

    /**
     * 添加空间
     * @param spaceAddRequest
     * @param loginUser
     * @return
     */
    @Override
    public long addSpace(SpaceAddRequest spaceAddRequest, User loginUser) {
         //1. 填充默认值
         Space space = new Space();
         BeanUtil.copyProperties(spaceAddRequest,space);
         String spaceName = space.getSpaceName();
         Integer spaceLevel = space.getSpaceLevel();
        if(StrUtil.isBlank(spaceName)){
            space.setSpaceName("默认空间");
        }
        if(spaceLevel==null){
            space.setSpaceLevel(SpaceLevelEnum.COMMON.getValue());
        }
        this.fillSpaceBySpaceLevel(space);
        //2. 校验参数
        this.validSpace(space,true);
        Long userId = loginUser.getId();
        space.setUserId(userId);
        //3. 校验权限，普通用户只能创建普通空间
        if(SpaceLevelEnum.COMMON.getValue()!=space.getSpaceLevel() &&!userService.isAdmin(loginUser)){
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "没有权限创建高级空间");
        }
        //4. 同一个用户只能创建一个空间(利用锁+事务，保证原子性)
        String lock=String.valueOf(loginUser.getId()).intern();
        synchronized (lock) {
            Long executeId = transactionTemplate.execute(status -> {
                QueryWrapper<Space> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("userId", loginUser.getId());
                boolean exists = this.exists(queryWrapper);
                if (exists) {
                    throw new BusinessException(ErrorCode.OPERATION_ERROR, "一个用户只能创建一个空间");
                }
                //5. 添加空间
                boolean save = this.save(space);
                if (!save) {
                    throw new BusinessException(ErrorCode.OPERATION_ERROR, "添加空间失败");
                }
                return space.getId();
            });
            return Optional.ofNullable(executeId).orElse(-1L);
        }
    }


}




